using System;
using System.Linq;
using MyCRM.Infrastructure.Repositories;
using MyCRM.Infrastructure.Storage;

namespace MyCRM.Infrastructure.Eventing
{
    public class EventSourceRepository : IEventSourceRepository
    {
        private readonly IEventStore _storage;

        public EventSourceRepository(IEventStore storage)
        {
            _storage = storage;
        }

        public void SaveEvents<T>(T aggregate, int version) where T : IAggregateRoot
        {
            _storage.SaveEvents(aggregate.AggregateId, version, aggregate.GetUncommittedChanges());
            aggregate.MarkChangesAsCommitted();
        }

        public T GetEventsBy<T>(Guid aggregateId) where T : IAggregateRoot, new()
        {
            var domainEventsForAggregate = _storage.GetEventsForEntity(aggregateId).ToList();
            var aggregate = new T();
            
            if(aggregate == null)
                throw new InvalidOperationException("Aggregate can't be created.");

            aggregate.ResotreFromEventHistory(domainEventsForAggregate);
        	
            return aggregate;
        }       
    }
}